package com.program.facesigninsystem.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.util.*;

/**
 * @author Mapler
 */
public class HttpClient {
    public static Map<String, Object> getWxUserOpenid(String code, String appId, String appSecret) {
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        //appid设置
        url.append("appid=");
        url.append(appId);
        //secret设置
        url.append("&secret=");
        url.append(appSecret);
        //code设置
        url.append("&js_code=");
        url.append(code);
        url.append("&grant_type=authorization_code");
        System.out.println(url);
        Map<String, Object> map = null;
        try {
            //构建一个Client
            CloseableHttpClient client = HttpClientBuilder.create().build();
            //构建一个GET请求
            HttpGet get = new HttpGet(url.toString());
            //提交GET请求
            CloseableHttpResponse response = client.execute(get);
            //拿到返回的HttpResponse的"实体"
            HttpEntity result = response.getEntity();
            String content = EntityUtils.toString(result);
            //打印返回的信息
            System.out.println(content);
            //把信息封装为json
            JSONObject res = JSONObject.parseObject(content);
            //把信息封装到map
            map = HttpClient.parseJsonToMap(res);
            //这个小工具的代码在下面
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    private static Map<String, Object> parseJsonToMap(JSONObject json) {

        // 最外层解析
        Map<String, Object> map = new HashMap<>();
        for (Object k : json.keySet()) {
            Object v = json.get(k);
        // 如果内层还是数组的话，继续解析
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<>();
                for (JSONObject json2 : (Iterable<JSONObject>) v) {
                    list.add(parseJsonToMap(json2));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }
}

